package com.wolfpire.workflow.spring.impl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.springframework.stereotype.Service;

import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.IBaseHibernateDao;
import com.wolfpire.system.common.base.service.impl.BaseHibernateService;
import com.wolfpire.system.model.User;
import com.wolfpire.workflow.dao.JbpmDao;
import com.wolfpire.workflow.dao.MyTaskDao;
import com.wolfpire.workflow.dao.WorkflowDao;
import com.wolfpire.workflow.om.MyTask;
import com.wolfpire.workflow.om.ProInstance;
import com.wolfpire.workflow.om.Workflow;
import com.wolfpire.workflow.spring.ProInstanceService;
import com.wolfpire.workflow.spring.WorkflowService;

@Service("workflowService")
public class WorkflowServiceImpl extends BaseHibernateService<Workflow, Long> implements WorkflowService {
	

	@Resource private WorkflowDao workflowDao;
	
	@Resource private MyTaskDao myTaskDao;
	
	@Resource private ProcessEngine processEngine;
	
	@Resource private ProInstanceService proInstanceService;
	
	@Resource private JbpmDao jbpmDao;
	
	@Override
	public List<Workflow> list(Workflow workflow) {
		return this.workflowDao.list(workflow);
	}

	@Override
	protected IBaseHibernateDao<Workflow, Long> getEntityDao() {
		return this.workflowDao;
	}

	@Override
	public Page<Workflow> setPageDataList(EasyuiPage<Workflow> page,
			Workflow filterWorkflow) {
		return this.workflowDao.findWorkflows(page, filterWorkflow);
	}

	@Override
	public void saveOrUpdate(Workflow workflow) {
		String flowXml = "";
		if (!StringUtils.isBlank(workflow.getFlowXml())) {
			flowXml = this.decodeString(workflow.getFlowXml()); 
			workflow.setFlowXml(flowXml);
		}
		String filePath = System.currentTimeMillis() + ".jpdl.xml";
		workflow.setFilePath(filePath);
		this.workflowDao.saveOrUpdate(workflow);
	}
	
	private String decodeString(String flowXml){
		String decodeStr = "";
		/*需要处理异常*/
		try {
			decodeStr = java.net.URLDecoder.decode(flowXml,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return decodeStr;
	}

	@Override
	public ProInstance startProcess(Long workFlowId, Long formId, User user,
			Map<String, Object> params) {
		// TODO Auto-generated method stub
		Workflow workflow = this.workflowDao.get(workFlowId);
		ProInstance proInstance = null;
		Long deploymentId = workflow.getDeploymentId();
		String flowName = workflow.getFlowName();
		params.put("formId", formId);
		params.put("workFlowId", workFlowId);
		params.put("formTypeId", workflow.getFormTypeId());
		params.put("userId", user.getId());
		params.put("deploymentId", deploymentId);
		System.out.println("*******************启动流程变量**********************");
		System.out.println(ToStringBuilder.reflectionToString(params));
		ExecutionImpl pi = (ExecutionImpl) processEngine.getExecutionService().startProcessInstanceByKey(flowName, params);
		proInstance = this.proInstanceService.addProInstance(workflow, pi, formId, user, params);
		System.out.println("*************************流程实例为*************************");
		System.out.println(ToStringBuilder.reflectionToString(proInstance));
		return proInstance;
	}

	@Override
	public String getDefXmlByDeployId(String deploymentId) {
		return this.jbpmDao.getDefXmlByDeployId(deploymentId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getFlowChart(Long instanceId) throws DocumentException {
		Map<String, Object> map = new HashMap<String, Object>();
		String nameId = null;
		ProInstance proInstance = proInstanceService.get(Long.valueOf(instanceId));
		nameId = proInstance.getNameId();
			
		Workflow workflow = workflowDao.get(proInstance.getWorkFlowId());
		
		String flowXml = "";
		if(String.valueOf(workflow.getDeploymentId()).equals(String.valueOf(proInstance.getDeploymentId()))){
			flowXml = workflow.getFlowXml();
		}else{
			flowXml = this.jbpmDao.getDefXmlByDeployId(String.valueOf(proInstance.getDeploymentId()));
		}
		
		Document doc = DocumentHelper.parseText(flowXml);
		Element root = doc.getRootElement();//获取根节点
		/* 解析任务节点 */
		Iterator<Element> nodeIterator = root.elementIterator();	 
		while(nodeIterator.hasNext()) {
			
			Element el = (Element)nodeIterator.next(); 
			String nodeName = el.attributeValue("name");
			//System.out.println("nodeName==="+nodeName);
			MyTask myTask = this.myTaskDao.getMyTask(instanceId.toString(), nodeName);
			if(myTask != null){
				el.addAttribute("isAudit", "1");
			} else {
				el.addAttribute("isAudit", "0");
			}

		}
		map.put("flowXml", doc.asXML());
		
		ProcessInstance processInstance = processEngine.getExecutionService().findProcessInstanceById(nameId);
		if(processInstance != null) {
			//通过processInstance获取所有活跃的节点
			Set<String> activitySet = processInstance.findActiveActivityNames();
			map.put("activitys", activitySet);
		} 
		return map;
	}
	
}
